package cn.nxcoder.blog.controller.admin;

import cn.nxcoder.blog.entity.User;
import cn.nxcoder.blog.service.UserService;
import cn.nxcoder.blog.util.MD5Utils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 后台登陆Controller
 *
 * @author shengwu ni
 * @date 2018/05/05 01:44
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 跳转到登陆页面
     * @return String
     */
    @GetMapping
    public String loginPage() {
        return "admin/login";
    }

    /**
     * 登陆接口
     * @param username 用户名
     * @param password 密码
     * @param session session
     * @param attributes attribute
     * @return String
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(username, MD5Utils.code(password));
        if (user != null) {
            user.setPassword(null);
            session.setAttribute("user", user);
            return "admin/index";
        } else {
            attributes.addFlashAttribute("message", "用户名或密码错误");
            // 重定向到上面loginPage方法
            return "redirect:/admin";
        }
    }

    /**
     * 注销
     * @param session session
     * @return String
     */
    @GetMapping("/logout")
    public String logOut(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }

}
